package com.leyou.upload.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.upload.config.OSSProperties;
import com.leyou.upload.service.UploadFileService;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author xiuer
 * @description 图片上传业务层
 * @create 2019/6/25 17:00
 */
@Service
public class UploadFileServiceImpl implements UploadFileService {
    private static final String IMAGE_DIR = "E:\\javaTool\\nginx-1.12.2\\html\\images";
    //请求图片的地址，默认80端口被nginx拦截去，去加载nginx的html目录的images内容
    private static final String IMAGE_URL = "http://image.leyou.com/images/";
    // 支持的文件类型
    private static final List<String> ALLOW_FILE_TYPE = Arrays.asList("image/png", "image/jpeg", "image/bmp");


    @Autowired
    private OSSProperties prop;

    @Autowired
    private OSS client;

    @Override
    public String uploadimage(MultipartFile file) {
        //校验图片类型
        String contentType = file.getContentType();
        if (!ALLOW_FILE_TYPE.contains(contentType)) {
            //类型不匹配
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        //校验图片内容
        try {
            BufferedImage readImage = ImageIO.read(file.getInputStream());
            //可能没有读取到内容
            if (readImage == null) {
                throw new RuntimeException();
            }
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        //文件存储地址
        //获取文件名全称  例：xxx.jpg
        String filename = file.getOriginalFilename();
        //获取文件类型  例：jpg
        String afterName = StringUtils.substringAfterLast(filename, ".");
        //获取一个随机数作为文件名
        String uuid = UUID.randomUUID().toString();
        filename = uuid + "." + afterName;
        File imagePath = new File(IMAGE_DIR, filename);
        //保存文件
        try {
            file.transferTo(imagePath);
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR, e);
        }
        //返回路径
        return IMAGE_URL + filename;
    }


    /**
     * 阿里OSS文件上传
     */
    @Override
    public Map<String, Object> getSignature() {
        try {
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}

